package com.pet.user.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    protected static MessageDigest messagedigest = null;

    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException exception) {
            System.err.println(Md5Util.class.getName() + "初始化失败，MessageDigest不支持MD5Util。");
            exception.printStackTrace();
        }
    }

    // MD5加密 生成32位md5码
    private static String md5Encode(String inStr) {
        byte[] byteArray = inStr.getBytes();
        byte[] md5Bytes = messagedigest.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    // 得到加密后的密码
    public static String getMD5String(String password, String salt) {
        return md5Encode(md5Encode(md5Encode(password)) + salt);
    }

    // 判断字符串的md5校验码是否与一个已知的md5码相匹配
    public static boolean checkPassword(String password, String salt, String md5PwdStr) {
        String s = getMD5String(password, salt);
        return s.equals(md5PwdStr);
    }
}
